package com.yunduo.module.listener;

import com.yunduo.common.YunDuoConst.OrderQueueParam;
import com.yunduo.common.YunDuoConst.OrderState;
import com.yunduo.entity.Order;
import com.yunduo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.yunduo.common.YunDuoConst.OrderQueueParam.ORDER_DELAY_QUEUE;

@Component
@Slf4j
public class OrderListener {

    @Resource
    private OrderService orderService;
    @Resource
    private RedisTemplate redisTemplate;

    //订单超时处理
    @RabbitHandler
    @RabbitListener(queues = "order.delay.queue")
    public void orderDealy(String orderId){
        if(orderId == null || orderId.length() == 0){
            log.info("订单为空");
            return;
        }
        //删除redis中的过期数据
        redisTemplate.delete(orderId);
        Order currentOrder = orderService.getById(orderId);
        //查看订单状态是否支付
        boolean isPay = currentOrder.getState().equals(OrderState.DELAY_PAY);
        if(isPay){
            currentOrder.setState(OrderState.PAY_CANCEL);
            orderService.updateById(currentOrder);
            log.info("用户 "+currentOrder.getUserId() + "的订单(" + currentOrder.getId() + ")超时,已取消");
        }
    }
}
